﻿using Furion.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.CMS.Core;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;

namespace Furion.CMS.Domain
{
    /// <summary>
    /// 审计日志
    /// </summary>
    [SuppressChangedListener]
    public partial class AuditLog : IEntity, IEntityTypeBuilder<AuditLog>
    {
        public AuditLog()
        {
            CreatedTime = DateTimeOffset.UtcNow;
        }

        /// <summary>
        /// 数据id
        /// </summary>
        public long Id { get; set; }
        /// <summary>
        /// 应用名称
        /// </summary>
        [MaxLength(200)]
        public string AppName { get; set; }
        /// <summary>
        /// 表名
        /// </summary>
        [MaxLength(200)]
        public string Table { get; set; }
        /// <summary>
        /// 操作方式
        /// </summary>
        [MaxLength(100)]
        public string Operate { get; set; }
        /// <summary>
        /// 行关键字
        /// </summary>
        [MaxLength(200)]
        public string RowKey { get; set; }
        /// <summary>
        /// 行内容
        /// </summary>
        [MaxLength(int.MaxValue)]
        public DbAuditContent[] RowContent { get; set; }
        /// <summary>
        /// 操作用户id
        /// </summary>
        public int UserId { get; set; }
        /// <summary>
        /// 操作用户
        /// </summary>
        public virtual UserInfo User { get; set; }
        /// <summary>
        /// IP地址
        /// </summary>
        public string IPAddress { get; set; }
        /// <summary>
        /// 创建日期
        /// </summary>
        public DateTimeOffset CreatedTime { get; set; }

        public void Configure(EntityTypeBuilder<AuditLog> entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            entityBuilder.UseDefaultTableNameDefine();

            entityBuilder.HasIndex(p => new { p.Id, p.UserId, p.CreatedTime });
            entityBuilder.Property(p => p.RowContent)
                .HasConversion(v => JsonConvert.SerializeObject(v), v => JsonConvert.DeserializeObject<DbAuditContent[]>(v));

            entityBuilder.HasOne(p => p.User)
                .WithMany()
                .HasForeignKey(p => p.UserId, false);
        }
    }
}
